import java.util.ArrayList;
import java.util.List;

public class LeetCode39 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        backtrack(candidates, target, res, new ArrayList<>(), 0);
        return res;
    }

    private void backtrack(int[] candidates, int target, List<List<Integer>> res, List<Integer> temp, int start) {
        //如果start等于数组的长度，直接返回
        if (start == candidates.length) {
            return;
        }
        if (target == 0) {
            res.add(new ArrayList<>(temp));
            return;
        }
        //直接跳过
        backtrack(candidates, target, res, temp, start + 1);

        // 选择当前数
        if (target - candidates[start] >= 0) {
            temp.add(candidates[start]);
            backtrack(candidates, target - candidates[start], res, temp, start);
            temp.remove(temp.size() - 1);
        }
    }
}
